<template>
  <div id="group_container" style="height: 98%">
    <el-card>
      <!-- 头部搜索 -->
      <div class="searchDiv">
        <div class="searchDivLeft">
          グループ名称：
          <el-input v-model="group.searchbean.subgroupName" placeholder="内容を入力してください" clearable style="width: 200px"></el-input>
          <el-button type="primary" v-preventReClick class="search" @click="getGroupItem"><i class="el-icon-search el-icon--left"></i>検索</el-button>
        </div>
        <div class="searchDivRight">
          <el-button type="primary" v-preventReClick @click="openDialogVisible" icon="el-icon-plus">新規</el-button>
          <el-button type="warning" v-preventReClick @click="addEdit" icon="el-icon-edit">修正</el-button>
          <el-button type="danger" v-preventReClick @click="remove" icon="el-icon-delete">削除</el-button>
        </div>
      </div>
      <!-- 主页表格部分 -->
      <el-table
        ref="multipleTable"
        :data="grouplist"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
        :header-cell-style="{ background: '#f2f2f2', color: '#606266' }"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="enterpriseName" label="会社名称"> </el-table-column>
        <el-table-column prop="subgroupName" label="グループ名称"> </el-table-column>
        <el-table-column prop="groupLeader" label="グループリーダー"></el-table-column>
        <el-table-column prop="staff" label="グループメンバー"> </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="group.indexPage"
          :page-size="group.pageSize"
          layout="total,prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 添加信息的对话框 -->
      <el-dialog v-model="addDialogVisible" width="50%" title="グループ情報新規" @close="handleClose">
        <!-- 内容主题区域 -->
        <span>
          <div class="add_container">
            <el-container>
              <el-aside width="35%">
                <div style="width: 100%; height: 100%">
                  <!-- 左侧树型数据部分 -->
                  <div style="width: 100%">
                    <el-tree :data="treeData" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current :props="defaultProps"> </el-tree>
                  </div>
                  <!-- <div style="width: 100%; height: 17%"> -->
                  <el-button class="Groupsetbtn" type="primary" icon="el-icon-circle-plus-outline" @click="getCheckedNodes()">追加</el-button>
                  <!-- </div> -->
                </div>
              </el-aside>
              <el-container style="width: 65%; height: 100%">
                <el-header style="height: 30%">
                  <table class="mytable" cellpadding="0" cellspacing="0" style="width: 100%">
                    <tr class="mytr">
                      <td class="mytd">会社の名前</td>
                      <td class="mytd1">江蘇華岡計算机系统有限公司</td>
                    </tr>
                    <tr class="mytr">
                      <td class="mytd">グループ名称</td>
                      <td class="mytd1">
                        <input type="text" placeholder="グループ名称を入力する" v-model="addForm.subgroupName" maxlength="20" style="width: 98%" />
                      </td>
                    </tr>
                    <tr class="mytr">
                      <td class="mytd">グループ順</td>
                      <td class="mytd1">
                        <input type="text" placeholder=" " v-model="addForm.sortFlag" maxlength="3" style="width: 98%" />
                      </td>
                    </tr>
                  </table>
                </el-header>
                <el-main>
                  <el-table :data="addForm.listSubgroupAndUserRelation" class="tableSet" border empty-text="無し" style="width: 100%">
                    <el-table-column prop="departName" label="部門"> </el-table-column>
                    <el-table-column prop="name" label="名前"> </el-table-column>
                    <el-table-column label="グループリーダー" width="160">
                      <template v-slot="scope">
                        <el-switch v-model="scope.row.manageFlag" active-value="1" inactive-value="0" active-text="はい" inactive-text="いいえ"></el-switch>
                      </template></el-table-column>
                    <el-table-column label="削除" width="50">
                      <template v-slot="scope">
                        <el-button type="primary" size="mini" icon="el-icon-delete" @click="removeGroup(scope.row.userGuid)"></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-main>
                <el-footer>
                  <el-button type="primary" icon="el-icon-circle-check" @click="saveGroup" v-preventReClick>新規</el-button>
                </el-footer>
              </el-container>
            </el-container>
          </div>
        </span>
      </el-dialog>
      <!-- 編輯信息的对话框 -->
      <el-dialog @close="editDialogClose" v-model="editVisible" width="50%" title="グループ情報修正">
        <!-- 内容主题区域 -->
        <div class="add_container">
          <el-container>
            <el-aside style="width: 35%">
              <div style="width: 100%; height: 100%">
                <!-- 左侧树型数据部分 -->
                <div style="width: 100%">
                  <el-tree :data="treeData" show-checkbox default-expand-all node-key="id" ref="tree1" highlight-current :props="defaultProps"> </el-tree>
                </div>
                <el-button class="Groupsetbtn" type="primary" icon="el-icon-circle-plus-outline" @click="getCheckedNodes()">追加</el-button>
              </div>
            </el-aside>
            <el-container style="width: 65%; height: 100%">
              <el-header style="height: 30%">
                <table class="mytable" cellpadding="0" cellspacing="0" style="width: 100%">
                  <tr class="mytr">
                    <td class="mytd">会社の名前</td>
                    <td class="mytd1">江蘇華岡計算机系统有限公司</td>
                  </tr>
                  <tr class="mytr">
                    <td class="mytd">グループ名称</td>
                    <td class="mytd1">
                      <input type="text" placeholder="グループ名称を入力する" v-model="addForm2.subgroupName" maxlength="20" style="width: 98%" />
                    </td>
                  </tr>
                  <tr class="mytr">
                    <td class="mytd">グループ順</td>
                    <td class="mytd1">
                      <input type="text" placeholder=" " maxlength="3" v-model="addForm2.sortFlag" style="width: 98%" />
                    </td>
                  </tr>
                </table>
              </el-header>
              <el-main>
                <!-- 小组成员表格部分 -->
                <!-- <el-divider content-position="left"
                    >グループメンバー情報</el-divider
                  > -->
                <el-table :data="addForm2.listSubgroupAndUserRelation" class="tableSet" border style="width: 100%">
                  <el-table-column prop="departName" label="部門"> </el-table-column>
                  <el-table-column prop="name" label="名前"> </el-table-column>
                  <el-table-column label="グループリーダー" width="160">
                    <template #default="scope"> <el-switch v-model="scope.row.manageFlag" active-value="1" inactive-value="0" active-text="はい" inactive-text="いいえ"> </el-switch> </template
                  ></el-table-column>
                  <el-table-column label="削除" width="50">
                    <template #default="scope">
                      <el-button type="primary" size="mini" icon="el-icon-delete" @click="removeGroup(scope.row.userGuid)" style="text-align: center"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-main>
              <el-footer style="margin: auto">
                <el-button type="primary" icon="el-icon-circle-check" @click="updataGroup" v-preventReClick>更新</el-button>
              </el-footer>
            </el-container>
          </el-container>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 狀態值
      // 獲取小組信息
      group: {
        searchbean: {
          subgroupName: ''
        },
        indexPage: 1,
        pageSize: 8
      },
      // 獲取過來的小組數組
      grouplist: [],
      total: 0,
      multipleSelection: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制編輯对话框的显示与隐藏
      editVisible: false,
      // 添加小组的提交的数据COPY
      addFormCopy: {},
      addFormCopy1: {},
      // 添加小组的提交的数据
      addForm: {
        subgroupGuid: '',
        groupEnterpriseGuid: this.$store.getters.showentergroup,
        subgroupName: '',
        sortFlag: 1,
        listSubgroupAndUserRelation: []
      },
      addForm1: {
        subgroupGuid: '',
        groupEnterpriseGuid: this.$store.getters.showentergroup,
        subgroupName: '',
        sortFlag: 1,
        listSubgroupAndUserRelation: []
      },
      // 编辑的绑定数据
      addForm2: {
        subgroupGuid: '',
        groupEnterpriseGuid: this.$store.getters.showentergroup,
        subgroupName: '',
        sortFlag: 1,
        listSubgroupAndUserRelation: []
      },
      // 樹形控件
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 樹形選中數據
      treeCheckout: [],
      // 編輯用户的表单数据
      editForm: {
        name: '',
        groupname: null,
        group: '',
        member: null
      },
      // 刪除數據id數組
      removeID: { ids: [] },
      addEditFlag: true
    }
  },
  // 頁面初加載
  created() {
    this.getGroupItem()
    if (this.editVisible === false) this.addForm = this.addForm1
  },
  mounted() {},
  methods: {
    getCheckedNodes() {
      // 聲明對象
      function ObjStory(name, userGuid, departName, manageFlag) {
        this.name = name
        this.userGuid = userGuid
        this.departName = departName
        this.manageFlag = manageFlag
      }
      if (this.addEditFlag === true) {
        this.treeCheckout = this.$refs.tree.getCheckedNodes()
        console.log(this.treeCheckout)
        for (var i = 0; i < this.treeCheckout.length; i++)
          if (this.treeCheckout[i].pid === this.$store.getters.showentergroup || this.treeCheckout[i].id === this.$store.getters.showentergroup) {
            this.treeCheckout.splice(i, 1)
            i--
          }
        console.log(this.treeCheckout)
        this.treeCheckout.forEach((item) => {
          let flag = 0
          this.addForm.listSubgroupAndUserRelation.forEach((ele) => {
            if (ele.userGuid === item.id) flag = 1
          })
          if (flag === 0) this.addForm.listSubgroupAndUserRelation.push(new ObjStory(item.name, item.id, item.pname, '0'))
        })
        console.log(this.addForm.listSubgroupAndUserRelation)
      }
      if (this.addEditFlag === false) {
        this.treeCheckout = this.$refs.tree1.getCheckedNodes()
        console.log(this.treeCheckout)
        //
        for (var i = 0; i < this.treeCheckout.length; i++)
          if (this.treeCheckout[i].pid === this.$store.getters.showentergroup || this.treeCheckout[i].id === this.$store.getters.showentergroup) {
            this.treeCheckout.splice(i, 1)
            i--
          }
        console.log(this.treeCheckout)
        this.treeCheckout.forEach((item) => {
          let flag = 0
          this.addForm2.listSubgroupAndUserRelation.forEach((ele) => {
            if (ele.userGuid === item.id) flag = 1
          })
          if (flag === 0) this.addForm2.listSubgroupAndUserRelation.push(new ObjStory(item.name, item.id, item.pname, '0'))
        })
        console.log(this.addForm2.listSubgroupAndUserRelation)
      }
    },
    handleClose() {
      this.$refs.tree.setCheckedKeys([])
      this.addForm.subgroupName = ''
      this.addForm.listSubgroupAndUserRelation = []
    },
    editDialogClose() {
      this.$refs.tree1.setCheckedKeys([])
      this.editVisible = false
      this.addForm2.listSubgroupAndUserRelation = []
      this.addForm2.subgroupName=''
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    // 分頁查詢數據
    getGroupItem() {
      this.axios
        .post('/subgroup/listSubgroup', this.group)
        .then((res) => {
          this.grouplist = res.data.data.list
          this.total = res.data.data.total
          this.getTreeData()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.group.pageSize = newSize
      this.getGroupItem()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.group.indexPage = newPage
      this.getGroupItem()
    },
    // 新增下方表格中小組的刪除
    removeGroup(groupID) {
      this.$confirm(this.$getMsg('I0004'), {
        cancelButtonText: 'キャンセル',
        confirmButtonText: '確認',
        type: 'warning'
      }).then(
        () => {
          let addCheckedKeys = []
          let editCheckedKeys = []
          console.log(this.addForm.listSubgroupAndUserRelation)
          this.addForm.listSubgroupAndUserRelation.forEach((item) => {
            addCheckedKeys.push(item.userGuid)
          })
          this.addForm.listSubgroupAndUserRelation.forEach((item, index) => {
            if (item.userGuid === groupID) {
              addCheckedKeys.splice(index, 1)
              this.$refs.tree.setCheckedKeys(addCheckedKeys)
              this.addForm.listSubgroupAndUserRelation.splice(index, 1)
            }
          })
          this.addForm2.listSubgroupAndUserRelation.forEach((item) => {
            editCheckedKeys.push(item.userGuid)
          })

          this.addForm2.listSubgroupAndUserRelation.forEach((item, index) => {
            if (item.userGuid === groupID) {
              editCheckedKeys.splice(index, 1)
              this.$refs.tree1.setCheckedKeys(editCheckedKeys)
              this.addForm2.listSubgroupAndUserRelation.splice(index, 1)
            }
          })
        },
        (res) => {
          console.log(res)
        }
      )
    },
    // 新增按钮小組信息
    async saveGroup() {
      console.log(this.addForm)
      this.addFormCopy = this.addForm
      let setTimeOut = 0
      this.addFormCopy.listSubgroupAndUserRelation.forEach((item) => {
        if (item.manageFlag === '1') {
          setTimeOut++
        } else item.manageFlag = '0'
      })
      if (setTimeOut === 0) return this.$message.warning('グループリーダーを選択してください。')
      if (setTimeOut > 1) return this.$message.warning('グループリーダーは１人だけを選択してください。')
      // グループリーダーは
      console.log(this.addFormCopy)
      const f = this.addFormCopy
      // if (f.sortFlag === '' || f.subgroupName === '' || f.listSubgroupAndUserRelation.length === 0) return this.$message.warning('データを空にしてはいけない')
      if (f.subgroupName === '') return this.$message.warning('グループ名称をご入力してください')
      if (f.sortFlag === '') return this.$message.warning('グループ順をご入力してください')
      if (f.listSubgroupAndUserRelation.length === 0) return this.$message.warning('人員を選択してください')
      // 新增小组请求
      this.axios
        .post('/subgroup/insert', this.addFormCopy)
        .then((res) => {
          console.log(res.data)
          if (res.data.success !== 1) {
            return this.$message.error(res.data.msg)
          }
          this.$message.success(this.$getMsg('I0001'))
          this.addDialogVisible = false
          this.getGroupItem()
          this.addForm.subgroupName = ''
          this.addForm.listSubgroupAndUserRelation = []
        })
        .catch((error) => {
          console.log(error)
        })
    },
    getTreeData() {
      this.axios
        .post('subgroup/groupEnterpriseGuid/treeUserInfo', {
          groupEnterpriseGuid: this.$store.getters.showentergroup
        })
        .then((res) => {
          console.log(res)
          this.treeData[0] = res.data.data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 編輯按钮小組信息
    addEdit() {
      this.addEditFlag = false
      // 获取树形数据
      // 声明对象
      function ObjStory(name, userGuid, departName, manageFlag) {
        this.name = name
        this.userGuid = userGuid
        this.departName = departName
        this.manageFlag = manageFlag
      }
      // 只能选中一条数据
      if (this.multipleSelection.length === 1) {
        this.group.searchbean.subgroupGuid = this.multipleSelection[0].subgroupGuid
        this.axios
          .post('/subgroup/listSubgroupAndUserRelation', this.group)
          .then((res) => {
            this.addForm2.listSubgroupAndUserRelation = []
            console.log(res.data)
            const groupList = res.data.data.list
            let editCheckedKeys = []
            console.log(groupList)
            this.addForm2.subgroupName = this.multipleSelection[0].subgroupName
            this.addForm2.subgroupGuid = groupList[0].subgroupGuid
            this.addForm2.sortFlag = 1
            groupList.forEach((item) => {
              editCheckedKeys.push(item.userGuid)
            })
            console.log(editCheckedKeys)
            this.$nextTick(() => {
              this.$refs.tree1.setCheckedKeys(editCheckedKeys)
            })
            groupList.forEach((item) => {
              this.addForm2.listSubgroupAndUserRelation.push(new ObjStory(item.userName, item.userGuid, item.departName, item.manageFlag))
            })
          })
          .catch((error) => {
            console.log(error)
          })

      } else {
        return this.$message({
          showClose: true,
          message: this.$getMsg('W0001'),
          type: 'warning'
        })
      }
      this.editVisible = true
    },
    // 更新修改小组信息
    updataGroup() {
      let setTimeOut = 0
      this.addFormCopy = this.addForm2
      this.addFormCopy.listSubgroupAndUserRelation.forEach((item) => {
        if (item.manageFlag === '1') {
        setTimeOut++}
        else item.manageFlag = '0'
      })
      const f = this.addFormCopy
      // if (f.sortFlag === '' || f.subgroupName === '' || f.listSubgroupAndUserRelation.length === 0) return this.$message.warning('データを空にしてはいけない')
      if (f.subgroupName === '') return this.$message.warning('グループ名称をご入力してください')
      if (f.sortFlag === '') return this.$message.warning('グループ順をご入力してください')
      if (f.listSubgroupAndUserRelation.length === 0) return this.$message.warning('人員を選択してください')
      if (setTimeOut === 0) return this.$message.warning('グループリーダーを選択してください。')
      if (setTimeOut > 1) return this.$message.warning('グループリーダーは１人だけを選択してください。')
      this.axios
        .put('/subgroup/update', this.addFormCopy)
        .then((res) => {
          if (res.data.success !== 1) {
            return this.$message.error(res.data.msg)
          }
          this.$message.success(this.$getMsg('I0002'))
          this.editVisible = false
          this.getGroupItem()
          this.addForm2 = this.addForm1
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 刪除小組信息
    remove() {
      this.removeID.ids = []
      this.multipleSelection.forEach((item) => {
        this.removeID.ids.push(item.subgroupGuid)
      })
      console.log(this.removeID.ids)
      if (this.multipleSelection.length === 0) {
        return this.$message({
          showClose: true,
          message: this.$getMsg('W0002'),
          type: 'warning',
          grouping: true
        })
      }
      this.$confirm(this.$getMsg('I0004'), {
        cancelButtonText: 'キャンセル',
        confirmButtonText: '確認',
        type: 'warning'
      }).then(
        () => {
          this.axios
            .delete('/subgroup/deleteById', { data: this.removeID })
            .then((res) => {
              this.$message.success(this.$getMsg('I0003'))
              this.getGroupItem()
              this.removeID.ids = []
            })
            .catch((error) => {
              console.log(error)
            })
        },
        (res) => {
          console.log(res)
        }
      )
    },
    openDialogVisible() {
      this.addEditFlag = true
      this.addForm = this.addForm1
      console.log(this.addForm1)
      this.addDialogVisible = true
      this.axios
        .post('subgroup/groupEnterpriseGuid/treeUserInfo', {
          groupEnterpriseGuid: this.$store.getters.showentergroup
        })
        .then((res) => {
          console.log(res)
          this.treeData[0] = res.data.data
        })
        .catch((error) => {
          console.log(error)
        })
    }
  }
}
</script>

<style scoped>
.flexset {
  display: flex;
  width: 98%;
  justify-content: flex-end;
}
.jiansuo {
  width: 100%;
}
/* 表格 */
.table {
  margin-top: 25px;
}
.tablestyle tr td {
  border: 1px solid gray;
}
.tablestyle tr td:nth-child(1) {
  width: 40%;
}
/* 添加小組 */
:deep(.add_container) {
  width: 100%;
}
.tableSet {
  height: 300px !important;
  overflow: auto;
}
.el-switch__label--left {
  margin-right: 0px !important;
}
/* 使select选择框的图标上下居中
  select選択ボックスのアイコンを上下中央にする*/
.el-input--mini .el-input__icon {
  line-height: 35px;
}
.el-footer {
  text-align: center;
}
.el-table::before {
  height: unset;
}
:deep(.el-dialog) {
  min-width: 700px;
  width: 50%;
}
:deep(.el-tree) {
  overflow: auto;
  height: 392px;
}
.Groupsetbtn {
  position: absolute;
  left: 105px;
  bottom: 50px;
}
</style>
